<?php
     /* HEADER */
 
     /* sql.mod.php */
 
/* orginaly by sykoi */
/* memcache functionality by hailey */
class sql {
 
    var $obj;
    var $query_id      = "";
    var $connection_id = "";
    private $memconn   = 0;
    var $query_count   = 0;
    var $cache_hit     = 0;
    var $record_row    = array();
    var $memcache_obj;
    var $memcache_servers = array('127.0.0.1:11211','192.168.1.143:11211');

 
    function __construct($conf) {
        debug ("Mysql module loaded.",0);
        $this->obj = $conf;
        $this->connect();

    }
 
    /*========================================================================*/
    // Connect to the database
    /*========================================================================*/
 
    function connect() {
        global $cache,$memcache_servers;

        if (isset($memcache_servers))
            $this->memcache_servers = $memcache_servers;


        if ($this->obj['persistent']) {
            $this->connection_id = mysql_pconnect( $this->obj['sql_host'], $this->obj['sql_user'],$this->obj['sql_pass']);
        } else {
            $this->connection_id = mysql_connect( $this->obj['sql_host'], $this->obj['sql_user'], $this->obj['sql_pass']);
        }
        if ( !mysql_select_db($this->obj['sql_database'], $this->connection_id) ) {
            echo ("ERROR: Cannot find database");
        }
        //Lets load memcache..
        if($this->obj['use_memcache'] == 1){
            //I added a new function.. memOn();
            if(!isset($cache)) {
                debug ('Unable to load default cache..',1);
                if ($this->memcache_obj = memOn()) {
                    debug('Created conf memcache..',0);
                    $this->memconn = 1;
                    return; //We're done here...
                }
            } else {
                debug('Found global memcache..',0);
                $this->memcache_obj = $cache;   //Since we have the global $cache, lets store it to our cache var..
                $this->memconn = 1;
                return; //We're done here..
            }

            $this->memcache_obj = new Memcache;
                foreach ($this->memcache_servers as $server) {
                    $serverinfo = explode(":",$server);
                    $this->memcache_obj->addServer($serverinfo[0],$serverinfo[1]);
                }
            $primary_memcache = explode(":",$this->memcache_servers[0]);
            if ($this->memcache_obj->connect($primary_memcache[0],$primary_memcache[1])){
                $this->memconn = 1;
            }
        }
    }
 
    /*========================================================================*/
    // Process a query
    /*========================================================================*/
    //todo: implement $fresh to force a new query, rather than one from cache.
 
    function query($the_query, $cached_name,$fresh = 0,$timeout = 45) {

        if($this->memconn == 1 AND $fresh == 0){
            $cache_return = $this->memcache_obj->get($cached_name.'array');
            if($cache_return){
                $this->cache_hit++;
                return $cache_return;
            }
        }
            if(!$this->query_id = mysql_query($the_query)) {
          		return mysql_error();
          	}

            $this->query_count++;
//            $this->obj["cached_queries"]["$cached_name"] = $this->query_id;

						$query_array = array();
						if($row = @mysql_fetch_array($this->query_id,MYSQL_ASSOC)) {
            do {
                $query_array[] = $row;
                $this->obj["cached_array"]["$cached_name"] = $query_array;
            }  while($row=mysql_fetch_array($this->query_id,MYSQL_ASSOC)); }

            if($this->memconn == 1){
                //$this->memcache_obj->set($cached_name,$this->obj,MEMCACHE_COMPRESSED,$timeout);
                $this->memcache_obj->set($cached_name.'array',$query_array,MEMCACHE_COMPRESSED,$timeout);
            }

        if (! $this->query_id ) {
            $this->fatal_error("mySQL query error: $the_query");
        }
 
   
        return $this->query_id;
    }
 
    /*========================================================================*/
    // Fetch a row based on the last query
    /*========================================================================*/
 
    function fetch_row($query_name) {
        $this->record_row = mysql_fetch_array($this->obj['cached_queries']["$query_name"], MYSQL_ASSOC);
        return $this->record_row;
    }

    function get_cache($query_name) {
        if($this->memconn==1) {
            $data = $this->memcache_obj->get($query_name.'array');
        } else {
					$data =& $this->obj["cached_array"]["$query_name"];
        }
        return $data;
    }
    
    function put_cache($key,$data,$timeout = 520){
        if($this->memconn==1) {
            $data = $this->memcache_obj->set($key,$data,MEMCACHE_COMPRESSED,$timeout);
        }
    }

    function ifData($key) {
        if($this->memconn!=1) {
            debug ("no connection to memcache");
            return;
        }
            if($data = $this->memcache_obj->get($key)){
                debug('datagot',0);
                return true;
            } else { return false; }
    }
 
		function getEnumArray($table,$enum) {
			$stable = mysql_escape_string($table);
			$senum = mysql_escape_string($enum);
			$query = "SHOW COLUMNS FROM `$table` LIKE '$senum'";
			
			$res = mysql_query($query);
      if( mysql_num_rows( $res ) > 0 ) {
				$row=mysql_fetch_array($res,MYSQL_ASSOC);
				preg_match_all("/'(.*?)'/", $row['Type'], $matches);
				$arryEnum= $matches[1];
			}
				return $arryEnum;
			
		}
    /*========================================================================*/
    // Fetch the number of rows affected by the last query
    /*========================================================================*/
 
    function affected_rows() {
        return mysql_affected_rows($this->connection_id);
    }
 
    /*========================================================================*/
    // Fetch the number of rows in a result set
    /*========================================================================*/
 
    function num_rows($cached_query) {
        $query_row_count = $this->obj['cached_queries']["$cached_query"];
        return mysql_num_rows($query_row_count);
    }
 
    /*========================================================================*/
    // Fetch the number of fields in a result set
    /*========================================================================*/
 
    function num_fields() {
        return mysql_num_fields($this->query_id);
    }
 
    /*========================================================================*/
    // Check to see if an entry already exists in a field
    /*========================================================================*/
 	//This is a count based query, please please please do not use unless you need to
	//use cache to store counters or something, count() on innodb without indexes can
	//kill. Just be wary of the overhead is all I'm saying.
    function entry_count($table, $field_name, $field_entry, $cached_name) {
        return $this->query("select count(*) from $table where $field_name='$field_entry'", "$cached_name");
    }
 
    /*========================================================================*/
    // Return the amount of queries used
    /*========================================================================*/
 
    function query_count() {
        return $this->query_count;
    }
 
    /*========================================================================*/
    // Free the result set from mySQLs memory
    /*========================================================================*/
 
    function free_result($query_id="") {
        if ($query_id == "") {
            $query_id = $this->query_id;
        }
 
        @mysql_free_result($query_id);
    }
 
    /*========================================================================*/
    // Shut down the database
    /*========================================================================*/
 
    function disconnect() { 
        return mysql_close($this->connection_id);
    }
 
    /*========================================================================*/
    // Basic error handler
    /*========================================================================*/
 
    function fatal_error($the_error) {
        $err = htmlspecialchars($the_error);
        die ("Mysql Error " . $err);
    }
 
   /* by athnex, check to see if connected */
   function is_connected() {
       return ($this->connection_id != "") ? OK : NOT_CONNECTED;
   }
}
 
?>
